import React, { useEffect, useState } from 'react'
import { Button, Table, Popconfirm, message } from 'antd'
import axios from 'axios'
import {
  DeleteOutlined,
  EditOutlined,
  UploadOutlined
} from '@ant-design/icons'


export default function NewsDraft(props) {
  const [dataSource, setdataSource] = useState([])
  const { username } = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    axios.get(`/news?author=${username}&auditState=0&_expand=category`).then(res => {
      setdataSource(res.data)
    })
  }, [username])

  const handleAudit = (id) => {
    axios.patch(`/news/${id}`, { auditState: 1 }).then(res =>
      setdataSource(dataSource.filter(data => data.id !== id))
    )
  };


  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`} >{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => {
              confirm(item)
            }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger shape="circle" icon={<DeleteOutlined />}></Button>
          </Popconfirm>

          <Button type="default" shape="circle" icon={<EditOutlined />} onClick={() => {
            props.history.push(`/news-manage/update/${item.id}`)
          }} />

          <Button shape="primary" onClick={() => { handleAudit(item.id) }} icon={<UploadOutlined />}></Button>
        </div>
      }

    },
  ];

  const delMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/news/${item.id}`)
  };

  const confirm = (item) => {
    message.success('Click on Yes');
    delMethod(item)
  };
  const cancel = (e) => {
    console.log(e);
  };


  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />
    </div>
  )
}
